<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitepage
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: IndexController.php 2011-05-05 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitepage_ProfileController extends Core_Controller_Action_Standard {
	
	//ACTION FOR SENDING A MESSGE TO PAGE OWNER
	public function messageOwnerAction() {
		
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//GET VIEWER DETAIL
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$viewer_id = $viewer->getIdentity ();
		
		//GET PAGE ID AND PAGE OBJECT
		$page_id = $this->_getParam ( "page_id" );
		$sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		
		//PAGE OWNER CAN'T SEND MESSAGE TO HIMSELF
		if ($viewer_id == $sitepage->owner_id) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		//FORM GENERATION
		$this->view->form = $form = new Messages_Form_Compose ();
		$form->setTitle ( 'Contact Page Owner' );
		$form->setDescription ( 'Create your message with the form given below. Your message will be sent to the admins of this Page.' );
		$form->removeElement ( 'to' );
		
		//GET ADMINS ID FOR SENDING MESSAGE
		$manageAdminData = Engine_Api::_ ()->getDbtable ( 'manageadmins', 'sitepage' )->getManageAdmin ( $page_id );
		$manageAdminData = $manageAdminData->toArray ();
		$ids = '';
		if (! empty ( $manageAdminData )) {
			foreach ( $manageAdminData as $key => $user_ids ) {
				$user_id = $user_ids ['user_id'];
				if ($viewer_id != $user_id) {
					$ids = $ids . $user_id . ',';
				}
			}
		}
		$ids = trim ( $ids, ',' );
		$form->toValues->setValue ( $ids );
		
		if (! $this->getRequest ()->isPost ()) {
			return;
		}
		
		$db = Engine_Api::_ ()->getDbtable ( 'messages', 'messages' )->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$values = $this->getRequest ()->getPost ();
			
			$form->populate ( $values );
			
			$is_error = 0;
			if (empty ( $values ['title'] )) {
				$is_error = 1;
			}
			
			//SENDING MESSAGE
			if ($is_error == 1) {
				$error = $this->view->translate ( 'Subject is required field !' );
				$error = Zend_Registry::get ( 'Zend_Translate' )->_ ( $error );
				
				$form->getDecorator ( 'errors' )->setOption ( 'escape', false );
				$form->addError ( $error );
				return;
			}
			
			$recipients = preg_split ( '/[,. ]+/', $values ['toValues'] );
			
			//LIMIT RECIPIENTS IF IT IS NOT A SPECIAL LIST OF MEMBERS
			$recipients = array_slice ( $recipients, 0, 1000 );
			
			//CLEAN THE RECIPIENTS FOR REPEATING IDS
			//THIS CAN HAPPEN IF RECIPIENTS IS SELECTED AND THEN A FRIEND LIST IS SELECTED
			$recipients = array_unique ( $recipients );
			
			$recipientsUsers = Engine_Api::_ ()->getItemMulti ( 'user', $recipients );
			
			$sitepage_title = $sitepage->title;
			$page_title_with_link = '<a href = http://' . $_SERVER ['HTTP_HOST'] . Zend_Controller_Front::getInstance ()->getRouter ()->assemble ( array ('page_url' => Engine_Api::_ ()->sitepage ()->getPageUrl ( $page_id ) ), 'sitepage_entry_view' ) . ">$sitepage_title</a>";
			
			$conversation = Engine_Api::_ ()->getItemTable ( 'messages_conversation' )->send ( $viewer, $recipients, $values ['title'], $values ['body'] . "<br><br>" . $this->view->translate ( "This message corresponds to the Page:" ) . $page_title_with_link );
			
			foreach ( $recipientsUsers as $user ) {
				if ($user->getIdentity () == $viewer->getIdentity ()) {
					continue;
				}
				Engine_Api::_ ()->getDbtable ( 'notifications', 'activity' )->addNotification ( $user, $viewer, $conversation, 'message_new' );
			}
			
			//INCREMENT MESSAGES COUNTER
			Engine_Api::_ ()->getDbtable ( 'statistics', 'core' )->increment ( 'messages.creations' );
			
			$db->commit ();
			
			return $this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => true, 'parentRefresh' => false, 'messages' => array (Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Your message has been sent successfully.' ) ) ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	}
	
	//ACTION FOR TELL TO THE FRIEND FOR THIS PAGE
	public function tellAFriendAction() {
		
		//DEFAULT LAYOUT
		$this->_helper->layout->setLayout ( 'default-simple' );
		
		//GET VIEWER DETAIL
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$viewr_id = $viewer->getIdentity ();
		
		//GET PAGE ID AND PAGE OBJECT
		$page_id = $this->_getParam ( 'page_id', $this->_getParam ( 'id', null ) );
		$sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		if (empty ( $sitepage ))
			return $this->_forward ( 'notfound', 'error', 'core' );
		
		//AUTHORIZATION CHECK FOR TELL A FRIEND
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'tfriend' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		//FORM GENERATION
		$this->view->form = $form = new Sitepage_Form_TellAFriend ();
		
		if (! empty ( $viewr_id )) {
			$value ['sender_email'] = $viewer->email;
			$value ['sender_name'] = $viewer->displayname;
			$form->populate ( $value );
		}
		
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			
			$values = $form->getValues ();
			
			//EDPLODES EMAIL IDS
			$reciver_ids = explode ( ',', $values ['sitepage_reciver_emails'] );
			
			if (! empty ( $values ['send_me'] )) {
				$reciver_ids [] = $values ['sitepage_sender_email'];
			}
			$sender_email = $values ['sitepage_sender_email'];
			
			//CHECK VALID EMAIL ID FORMITE
			$validator = new Zend_Validate_EmailAddress ();
			
			if (! $validator->isValid ( $sender_email )) {
				$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Invalid sender email address value' ) );
				return;
			}
			foreach ( $reciver_ids as $reciver_id ) {
				$reciver_id = trim ( $reciver_id, ' ' );
				if (! $validator->isValid ( $reciver_id )) {
					$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Please enter correct email address of the receiver(s).' ) );
					return;
				}
			}
			$sender = $values ['sitepage_sender_name'];
			$message = $values ['sitepage_message'];
			$heading = ucfirst ( $sitepage->getTitle () );
			Engine_Api::_ ()->getApi ( 'mail', 'core' )->sendSystem ( $reciver_ids, 'SITEPAGE_TELLAFRIEND_EMAIL', array ('host' => $_SERVER ['HTTP_HOST'], 'sender_name' => $sender, 'page_title' => $heading, 'message' => '<div>' . $message . '</div>', 'object_link' => 'http://' . $_SERVER ['HTTP_HOST'] . Engine_Api::_ ()->sitepage ()->getHref ( $sitepage->page_id, $sitepage->owner_id, $sitepage->getSlug () ), 'sender_email' => $sender_email, 'queue' => true ) );
			
			$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => true, 'parentRefresh' => false, 'format' => 'smoothbox', 'messages' => array (Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Your message to your friend has been sent successfully.' ) ) ) );
		}
	}
	
	//ACTION FOR PRINTING THE PAGE
	public function printAction() {
		$this->_helper->layout->setLayout ( 'default-simple' );
		//GET PAGE ID AND PAGE OBJECT
		$this->view->page_id = $page_id = $this->_getParam ( 'page_id', $this->_getParam ( 'id', null ) );
		$this->view->sitepage = $sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		if (empty ( $sitepage ))
			return $this->_forward ( 'notfound', 'error', 'core' );
		
		//AUTHORIZATION CHECK FOR PRINTING
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'print' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		if ($sitepage->category_id != 0)
			$this->view->category = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $sitepage->category_id );
		
		if ($sitepage->subcategory_id != 0)
			$this->view->subcategory = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $sitepage->subcategory_id );
		
		if ($sitepage->subsubcategory_id != 0)
			$this->view->subsubcategory = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $sitepage->subsubcategory_id );
	}
	
	//ACTION FOR WRITE BOX AT VIEW PROFILE PAGE
	public function displayAction() {
		
		//GET THE TEXT STRING
		$text = $this->_getParam ( 'text_string' );
		
		//GET PAGE ID
		$page_id = $this->_getParam ( 'page_id' );
		
		$writesTable = Engine_Api::_ ()->getDbtable ( 'writes', 'sitepage' )->setWriteContent ( $page_id, $text );
		exit ();
	}

}
?>